package com.github.iot.utils;

import android.content.Context;
import android.text.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * TODO
 *
 * @Author: 梁声洪
 * @Date: 2019/12/7 14:52
 * @Version: v1.0.0
 */
public class CommonUtils {

    private static Context context;

    /**
     * 初始化工具类
     *
     * @param context 上下文
     */
    public static void init(Context context) {
        CommonUtils.context = context.getApplicationContext();
    }

    /**
     * 在某种获取不到 Context 的情况下，即可以使用才方法获取 Context
     * 获取ApplicationContext
     *
     * @return ApplicationContext
     */
    public static Context getContext() {
        if (context != null) {
            return context;
        }
        throw new NullPointerException("请先调用init()方法");
    }

    /**
     * 判断是否IP
     *
     * @param ipStr
     * @return
     */
    public static boolean isIp(String ipStr) {
        if (TextUtils.isEmpty(ipStr)) {
            return false;
        }

        Pattern pattern = Pattern.compile("^(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)){3}");
        Matcher matcher = pattern.matcher(ipStr);
        return matcher.matches();
    }

}